package com.spring.sunflower.main.fragment;


import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.spring.sunflower.R;
import com.spring.sunflower.anchor.PersonalDetailActivity;
import com.spring.sunflower.base.BaseFragment;
import com.spring.sunflower.bean.BannerBean;
import com.spring.sunflower.bean.RecommendAnchorsBean;
import com.spring.sunflower.common.WebViewActivity;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.conversation.ChatVideoActivity;
import com.spring.sunflower.dialog.OnPermissionIntroClickListener;
import com.spring.sunflower.main.MainContract;
import com.spring.sunflower.main.adapter.ImageBannerAdapter;
import com.spring.sunflower.main.adapter.NewDiscoverAdapter;
import com.spring.sunflower.main.presenter.LivelyPresenter;
import com.spring.sunflower.widget.GridDividerItemDecoration;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Kevin on 2021/5/28<br/>
 * <p>
 * Describe:<br/>
 */
public class NewDiscoverFragment extends BaseFragment<LivelyPresenter> implements
        MainContract.LivelyView, OnLoadMoreListener, OnRefreshListener {
    private SmartRefreshLayout refreshLayout;
    private RecyclerView mRecyclerView;
    private List<RecommendAnchorsBean.DatasBean> mData = new ArrayList<>();
    private NewDiscoverAdapter mAdapter;
    private Banner banner;
    private List<BannerBean.DatasBean> bannerData = new ArrayList<>();
    private ImageBannerAdapter bannerAdapter;
    private int pageIndex = 1;
    private String userID;
    private String memberId;
    private String mOtherFaceUrl;
    private String mOtherName;
    private int showCount = 0;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            ++showCount;
            if (showCount > 1) {
                mPresenter.getRecommendAnchorsFruit(1);
                pageIndex = 1;
            }
        } else {

        }
    }

    @Override
    public int setLayoutResId() {
        return R.layout.fragment_lively;
    }

    @Override
    public void initView() {
        userID = getField(Constant.KEY_USERID, "");
        refreshLayout = mView.findViewById(R.id.refreshLayout);
        mRecyclerView = mView.findViewById(R.id.rvRecyclerView);
        GridLayoutManager layoutManager = new GridLayoutManager(mActivity, 2);
        mRecyclerView.setLayoutManager(layoutManager);
        GridDividerItemDecoration gridDividerItemDecoration = new GridDividerItemDecoration(mActivity);
//        mRecyclerView.addItemDecoration(gridDividerItemDecoration);
        mAdapter = new NewDiscoverAdapter(R.layout.adapter_recommend_new_discover, mData);
        mAdapter.addHeaderView(getHeaderView());
        mRecyclerView.setAdapter(mAdapter);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setOnRefreshListener(this);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                RecommendAnchorsBean.DatasBean datasBean = mData.get(position);
                Intent intent = new Intent(getActivity(), PersonalDetailActivity.class);
                intent.putExtra(Constant.KEY_TARGET_ID, String.valueOf(datasBean.getMemberId()));
                startActivity(intent);
            }
        });
        mAdapter.addChildClickViewIds(R.id.ivHello);
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                RecommendAnchorsBean.DatasBean datasBean = mData.get(position);
                String status = datasBean.getStatus();
                memberId = datasBean.getMemberId();
                mOtherFaceUrl = datasBean.getPhoto();
                mOtherName = datasBean.getNickname();
                saveField(Constant.KEY_USERID_CHATTER, memberId);
                saveField(Constant.KEY_AVATAR_CHATTER, mOtherFaceUrl);
                saveField(Constant.KEY_NICKNAME_CHATTER, mOtherName);
                if (status.equals("4")) {
                    if (!XXPermissions.isGranted(mActivity, Permission.RECORD_AUDIO) || !XXPermissions.isGranted(mActivity, Permission.CAMERA)) {
                        showPermissionIntroDialog(new String[]{getString(R.string.permission_audio_title), getString(R.string.permission_camera_title)}, new String[]{getString(R.string.permission_audio_desc), getString(R.string.permission_camera_desc)}, new OnPermissionIntroClickListener() {
                            @Override
                            public void onClickOK() {
                                XXPermissions.with(mActivity)
                                        .permission(Permission.RECORD_AUDIO, Permission.CAMERA)
                                        .request(new OnPermissionCallback() {
                                            @Override
                                            public void onGranted(List<String> permissions, boolean all) {
                                                if (all) {
                                                    mPresenter.applyChat(userID, memberId);
                                                } else {
                                                    showPermissionIntroDialog(getString(R.string.permission_denied_title), "无法正常进行视频通话", null);
                                                }
                                            }

                                            @Override
                                            public void onDenied(List<String> permissions, boolean never) {
                                                showPermissionIntroDialog(getString(R.string.permission_denied_title), "无法正常进行视频通话", null);
                                            }
                                        });
                            }

                            @Override
                            public void onClickCancel() {

                            }
                        });
                    } else {
                        mPresenter.applyChat(userID, memberId);
                    }
                } else {
                    mPresenter.sayHello(memberId);
                }

            }
        });
    }

    private View getHeaderView() {
        View view = getLayoutInflater().inflate(R.layout.header_lively, (ViewGroup) mRecyclerView.getParent(), false);
        banner = view.findViewById(R.id.banner);
        bannerAdapter = new ImageBannerAdapter(mActivity, bannerData);
        banner.setAdapter(bannerAdapter);
//        banner.setBannerGalleryMZ(20);
//        banner.setBannerGalleryEffect(20, 10);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(Object data, int position) {
                BannerBean.DatasBean datasBean = bannerData.get(position);
                Intent intent = new Intent(mActivity, WebViewActivity.class);
                intent.putExtra(Constant.KEY_WEB_VIEW_TITLE, datasBean.getBannerName());
                intent.putExtra(Constant.KEY_WEB_VIEW_URL, datasBean.getJumpUrl());
                startActivity(intent);
            }
        });
        return view;
    }

    @Override
    public void initData() {

    }

    @Override
    public void initListener() {

    }

    @Override
    public void loadData() {
        mPresenter.getBanner();
        mPresenter.getRecommendAnchorsFruit(1);
    }

    @Override
    public LivelyPresenter setPresenter() {
        return new LivelyPresenter(this);
    }

    @Override
    public void showAnchorData(List<RecommendAnchorsBean.DatasBean> data) {
//        printD("mDta.size=" + mData.size());
        if (pageIndex == 1) {
            mData.clear();
            mAdapter.setList(mData);
        }
        mAdapter.addData(data);
    }

    @Override
    public void showBannerData(List<BannerBean.DatasBean> data) {
        bannerAdapter.updateData(data);
    }

    @Override
    public void liveApplySuccess() {
        Intent intent = new Intent(mActivity, ChatVideoActivity.class);
        intent.putExtra(Constant.VIDEO_CALL_SELF_DIAL, true);
        intent.putExtra(Constant.VIDEO_CALL_OTHER_ID, memberId);
        intent.putExtra(Constant.VIDEO_CALL_OTHER_FACE_URL, mOtherFaceUrl);
        intent.putExtra(Constant.VIDEO_CALL_OTHER_NICKNAME, mOtherName);
        startActivity(intent);
    }

    @Override
    public void sayHelloSuccess() {
        showToast("打招呼成功");
    }

    @Override
    public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
        if (refreshLayout.isLoading()) {
            refreshLayout.finishLoadMore();
        }
        mPresenter.getRecommendAnchorsFruit(++pageIndex);
    }

    @Override
    public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh();
        }
        pageIndex = 1;
        mPresenter.getRecommendAnchorsFruit(1);
    }
}
